package main.resources.controller.dao.moodle;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import main.resources.controller.dao.Observer;
import main.resources.controller.dao.Subject;

public class PersistenceUnity implements Subject {

	private EntityManagerFactory emf = Persistence.createEntityManagerFactory("moodle");
	private EntityManager em;	
    
	protected List<Observer> observers = new ArrayList<Observer>();
	
    protected EntityManager getEm() {
    	if (em == null)
			em = emf.createEntityManager();   	
    	return em; 
    }
    
    protected void endTransaction () {
        if (getEm().isOpen()) {
            getEm().close();
            em = null;
        }
    }

	@Override
	public void registerObserver(Observer observer) {
		if (!observers.contains(observer)) {
            observers.add(observer);
        }
	}

	@Override
	public void removeObserver(Observer observer) {
		if (observers.contains(observer)) {
            observers.remove(observer);
        }
	}

	@Override
	public void notifyObservers(Object arg) {
		for (Observer observer : observers) {
            observer.update(arg);
        }		
	}
	
}
